<?php
/**
 * 邀请返利逻辑层
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\logic;

use app\common\logic\LogicBase;

class Invite extends LogicBase
{
    /**
     * 获取邀请相关数据搜索条件（兼容性方法，建议使用具体的getXxxWhere方法）
     */
    public function getWhere($data = [])
    {
        return $this->getInviteRecordWhere($data);
    }

    /**
     * 获取邀请记录搜索条件
     */
    public function getInviteRecordWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索（邀请人或被邀请人）
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        !empty($data['inviter_id']) && $where['inviter_id'] = $data['inviter_id'];
        !empty($data['invitee_id']) && $where['invitee_id'] = $data['invitee_id'];
        
        // 邀请码搜索
        !empty($data['invite_code']) && $where['invite_code'] = $data['invite_code'];
        
        // 状态搜索
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 结算状态搜索
        isset($data['settlement_status']) && $data['settlement_status'] !== '' && $where['settlement_status'] = $data['settlement_status'];
        
        // 搜索条件：用户昵称、手机号
        !empty($data['search_data']) && $where['nickname|mobile'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 获取余额记录搜索条件
     */
    public function getBalanceRecordWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 记录类型搜索
        !empty($data['type']) && $where['type'] = $data['type'];
        
        // 金额范围搜索
        !empty($data['min_amount']) && $where['amount'] = ['>=', $data['min_amount']];
        !empty($data['max_amount']) && $where['amount'] = ['<=', $data['max_amount']];
        
        // 搜索条件：描述内容
        !empty($data['search_data']) && $where['description'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 时间范围搜索
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 获取提现订单搜索条件
     */
    public function getWithdrawOrderWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 提现单号搜索
        !empty($data['withdraw_no']) && $where['withdraw_no'] = ['like', '%' . $data['withdraw_no'] . '%'];
        
        // 提现类型搜索
        !empty($data['withdraw_type']) && $where['withdraw_type'] = $data['withdraw_type'];
        
        // 状态搜索
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 金额范围搜索
        !empty($data['min_amount']) && $where['amount'] = ['>=', $data['min_amount']];
        !empty($data['max_amount']) && $where['amount'] = ['<=', $data['max_amount']];
        
        // 申请时间范围搜索
        !empty($data['start_time']) && $where['apply_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['apply_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['apply_time']) && is_string($data['apply_time'])) {
            $date = $data['apply_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['apply_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }

    /**
     * 生成邀请码
     */
    public function generateInviteCode($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 检查是否已有邀请码
            $existCode = $this->modelUser->getValue(['id' => $userId], 'invite_code');
            if ($existCode) {
                return [RESULT_SUCCESS, '获取成功', ['invite_code' => $existCode]];
            }
            
            // 生成新的邀请码（与用户ID强相关）
            $inviteCode = $this->createUniqueInviteCode($userId);
            
            // 更新用户邀请码
            $result = $this->modelUser->updateInfo(['id' => $userId], ['invite_code' => $inviteCode]);
            
            if ($result) {
                return [RESULT_SUCCESS, '生成成功', ['invite_code' => $inviteCode]];
            } else {
                return [RESULT_ERROR, '生成失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '生成失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 创建唯一邀请码
     */
    private function createUniqueInviteCode($userId)
    {
        // 规则：BASE36(userId) + 4位校验（md5(userId + 系统JWT_KEY)）
        $base36 = strtoupper(base_convert((string) $userId, 10, 36));
        $secret = (string) config('jwt_key');
        $hash = strtoupper(substr(md5($userId . '|' . $secret), 0, 4));
        $code = $base36 . $hash;
        
        // 若碰撞则附加一位重试（极低概率）
        $suffix = 0;
        while ($this->modelUser->getValue(['invite_code' => $code], 'id')) {
            $suffix++;
            $code = $base36 . $hash . $suffix;
        }
        
        return $code;
    }
    
    /**
     * 处理邀请关系
     */
    public function processInviteRelation($data = [])
    {
        try {
            $inviteeId = $data['invitee_id'] ?? 0;
            $inviteCode = $data['invite_code'] ?? '';
            
            if (!$inviteeId || !$inviteCode) {
                return [RESULT_ERROR, '参数不完整'];
            }
            
            // 若用户已存在邀请人，则不允许修正
            $invitee = $this->modelUser->getInfo(['id' => $inviteeId], 'id,inviter_id');
            if ($invitee && intval($invitee['inviter_id']) > 0) {
                return [RESULT_ERROR, '该用户已存在邀请人'];
            }
            
            // 查找邀请人
            $inviter = $this->modelUser->getInfo(['invite_code' => $inviteCode, 'status' => 1], 'id,nickname');
            if (!$inviter) {
                return [RESULT_ERROR, '邀请码无效'];
            }
            
            $inviterId = $inviter['id'];
            
            // 检查是否自己邀请自己
            if ($inviterId == $inviteeId) {
                return [RESULT_ERROR, '不能邀请自己'];
            }
            
            // 检查是否试图将自己邀请的用户作为邀请人（反向绑定）
            $reverse = $this->modelInviteRecord->getInfo(['inviter_id' => $inviteeId, 'invitee_id' => $inviterId]);
            if ($reverse) {
                return [RESULT_ERROR, '不能将自己邀请的用户设为邀请人'];
            }
            
            // 检查是否已被邀请（记录层）
            $existInvite = $this->modelInviteRecord->getInfo(['invitee_id' => $inviteeId]);
            if ($existInvite) {
                return [RESULT_ERROR, '该用户已被邀请'];
            }
            
            // 获取佣金比例配置
            $commissionRate = 0.1; // 默认10%，可从配置获取
            
            // 创建邀请记录
            $inviteData = [
                'inviter_id' => $inviterId,
                'invitee_id' => $inviteeId,
                'invite_code' => $inviteCode,
                'commission_rate' => $commissionRate,
                'commission_amount' => 0,
                'settlement_status' => 0,
                'status' => 1,
                'create_time' => time(),
                'update_time' => time()
            ];
            
            $inviteId = $this->modelInviteRecord->updateInfo([], $inviteData);
            
            // 同步写入用户表的邀请人（仅当为空时）
            if ($inviteId) {
                $this->modelUser->updateInfo(['id' => $inviteeId, 'inviter_id' => 0], ['inviter_id' => $inviterId]);
            }
            
            if ($inviteId) {
                return [RESULT_SUCCESS, '邀请关系建立成功'];
            } else {
                return [RESULT_ERROR, '邀请关系建立失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '处理失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户邀请统计
     */
    public function getUserInviteStats($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 邀请人数
            $invitedUsers = $this->modelInviteRecord->stat(['inviter_id' => $userId, 'status' => 1]);
            
            // 累计佣金（邀请记录中的佣金累计）
            $totalCommission = $this->modelInviteRecord->stat(['inviter_id' => $userId, 'status' => 1], 'sum', 'commission_amount');
            
            // 可提现余额（用户余额）
            $user = $this->modelUser->getInfo(['id' => $userId]);
            $withdrawableAmount = $user ? ($user['available_amount'] ?? 0) : 0;
            
            // 提现总额（已处理的提现订单）
            $withdrawnAmount = 0;
            if (property_exists($this, 'modelWithdrawOrder')) {
                $withdrawnAmount = $this->modelWithdrawOrder->stat(['user_id' => $userId, 'status' => 1], 'sum', 'amount');
            }
            
            // 会员人数（被邀请用户的VIP订单支付成功数量）
            $vipUsers = 0;
            if (property_exists($this, 'modelVipOrder')) {
                $vipUsers = $this->modelVipOrder->stat(['inviter_id' => $userId, 'status' => 'paid']);
            }
            
            $result = [
                'withdrawable_amount' => number_format($withdrawableAmount, 2),
                'invited_users' => intval($invitedUsers),
                'vip_users' => intval($vipUsers),
                'withdrawn_amount' => number_format($withdrawnAmount, 2),
                'total_commission' => number_format($totalCommission, 2)
            ];
            
            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户余额信息
     */
    public function getUserBalance($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $user = $this->modelUser->getInfo(['id' => $userId]);
            
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $balance = [
                'available_amount' => $user['available_amount'] ?? 0,
                'total_earnings' => $user['total_earnings'] ?? 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $balance];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取邀请列表
     */
    public function getInviteList($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            $limit = intval($data['limit'] ?? DB_LIST_ROWS);
            $this->modelInviteRecord->alias('ir');
            $this->modelInviteRecord->join = [
                [SYS_DB_PREFIX . 'user u', 'u.id = ir.invitee_id', 'LEFT'],
                [SYS_DB_PREFIX . 'picture pic', 'pic.id = u.avatar_id', 'LEFT'],
            ];
            $where = ['ir.inviter_id' => $userId, 'ir.status' => 1];
            $field = 'u.id as id, u.nickname, IFNULL(pic.path, u.avatar_url) AS avatar, ir.create_time';
            $order = 'ir.create_time desc';
            $list = $this->modelInviteRecord->getList($where, $field, $order, $limit);
            $hasMore = is_array($list) && count($list) >= $limit;
            return [RESULT_SUCCESS, '获取成功', ['list' => $list, 'has_more' => $hasMore]];
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取佣金记录
     */
    public function getCommissionLog($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }

            $page = intval($data['page'] ?? 1);
            $limit = intval($data['page_size'] ?? ($data['list_rows'] ?? DB_LIST_ROWS));

            $type = $data['type'] ?? 'all';
            if ($type === 'income') {
                $typeWhere = ['commission'];
            } elseif ($type === 'withdraw') {
                $typeWhere = ['withdraw'];
            } else {
                $typeWhere = ['commission', 'withdraw'];
            }

            $where = [
                'user_id' => $userId,
                'type' => ['in', $typeWhere]
            ];

            $field = 'id,amount,description,status,create_time,type';
            $order = 'id desc';

            // 列表数据（遵循分页参数为数字的规范）
            $rows = $this->modelBalanceRecord->getList($where, $field, $order, $limit);

            // 统计汇总
            $totalCommission = floatval($this->modelBalanceRecord->stat(['user_id' => $userId, 'type' => 'commission', 'status' => 1], 'sum', 'amount'));
            $withdrawSum = floatval($this->modelBalanceRecord->stat(['user_id' => $userId, 'type' => 'withdraw', 'status' => 1], 'sum', 'amount'));
            $withdrawnAmount = abs($withdrawSum);
            $availableAmount = floatval($this->modelUser->getValue(['id' => $userId], 'available_amount'));

            // 统计总数与分页
            $total = intval($this->modelBalanceRecord->stat($where, 'count', 'id'));
            $lastPage = $limit > 0 ? intval(ceil($total / $limit)) : 1;
            $currentPage = max(1, min($page, $lastPage));
            $hasMore = $currentPage < $lastPage;

            // 映射字段以适配前端展示
            $list = [];
            foreach ($rows as $r) {
                $isIncome = ($r['type'] === 'commission');
                $statusText = ($r['status'] == 1) ? 'success' : 'pending';
                $list[] = [
                    'id' => $r['id'],
                    'title' => $isIncome ? '佣金入账' : '提现扣减',
                    'desc' => $r['description'] ?? ($isIncome ? '邀请好友获得佣金' : '提现申请'),
                    'type' => $isIncome ? 'income' : 'withdraw',
                    'status' => $statusText,
                    'amount' => $isIncome ? floatval($r['amount']) : abs(floatval($r['amount'])),
                    'create_time' => is_numeric($r['create_time']) ? intval($r['create_time']) : $r['create_time']
                ];
            }

            $result = [
                'stats' => [
                    'total_commission' => number_format($totalCommission, 2),
                    'available_amount' => number_format($availableAmount, 2),
                    'withdrawn_amount' => number_format($withdrawnAmount, 2)
                ],
                'list' => $list,
                'current_page' => $currentPage,
                'last_page' => $lastPage,
                'per_page' => $limit,
                'total' => $total,
                'has_more' => $hasMore
            ];

            return [RESULT_SUCCESS, '获取成功', $result];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 生成虚拟佣金数据
     */
    private function generateMockCommissionData($limit = 20)
    {
        $mockData = [];
        $amounts = [2.9, 29.9, 59.9, 8.7, 15.6, 23.4, 45.8, 12.3, 67.2, 34.5];
        
        for ($i = 0; $i < $limit; $i++) {
            $mockData[] = [
                'id' => $i + 1,
                'amount' => $amounts[$i % count($amounts)],
                'description' => '邀请好友获得佣金',
                'create_time' => date('Y-m-d H:i:s', time() - $i * 3600)
            ];
        }
        
        return $mockData;
    }
    
    /**
     * 申请提现
     */
    public function applyWithdraw($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $amount = $data['amount'] ?? 0;
            $withdrawType = $data['withdraw_type'] ?? 'wechat';
            $accountInfo = $data['account_info'] ?? '';
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($amount <= 0) {
                return [RESULT_ERROR, '提现金额必须大于0'];
            }
            
            if (empty($accountInfo)) {
                return [RESULT_ERROR, '账户信息不能为空'];
            }
            
            // 检查用户可提现余额
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $availableBalance = $user['available_amount'];
            if ($amount > $availableBalance) {
                return [RESULT_ERROR, '可提现余额不足'];
            }
            
            // 提现限制检查
            if ($amount < 10) {
                return [RESULT_ERROR, '最低提现金额为10元'];
            }
            
            // 计算手续费（1%，最低1元）
            $feeRate = 0.01;
            $fee = max($amount * $feeRate, 1);
            $actualAmount = $amount - $fee;
            
            if ($actualAmount <= 0) {
                return [RESULT_ERROR, '扣除手续费后金额不足'];
            }
            
            // 生成提现单号
            $withdrawNo = 'WD' . date('YmdHis') . rand(1000, 9999);
            
            // 使用Withdraw逻辑层处理提现申请
            $withdrawLogic = new \app\common\logic\Withdraw();
            $withdrawData = [
                'user_id' => $userId,
                'amount' => $amount,
                'withdraw_type' => $withdrawType,
                'account_info' => $accountInfo,
                'remark' => '邀请返利提现'
            ];
            
            $result = $withdrawLogic->applyWithdraw($withdrawData);
            
            if ($result[0] == RESULT_SUCCESS) {
                return [RESULT_SUCCESS, '提现申请成功', $result[2]];
            } else {
                return [RESULT_ERROR, $result[1]];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '申请失败：' . $e->getMessage()];
        }
    }
    

    
    /**
     * 获取提现记录
     */
    public function getWithdrawLog($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            $where = ['user_id' => $userId];
            $field = 'id,withdraw_no,amount,fee,actual_amount,withdraw_type,status,apply_time,process_time';
            $order = 'id desc';
            $paginate = ['list_rows' => $limit, 'page' => $page];
            
            $list = $this->modelWithdrawOrder->getList($where, $field, $order, $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取邀请返利规则
     */
    public function getInviteRules($data = [])
    {
        try {
            $rules = [
                'commission_rate' => '10%',
                'min_withdraw' => '10.00',
                'withdraw_fee' => '2%',
                'rules' => [
                    '1. 邀请好友注册成功即可获得佣金奖励',
                    '2. 好友充值VIP会员，您可获得10%的佣金返利',
                    '3. 佣金实时到账，可随时提现',
                    '4. 最低提现金额为10元，提现手续费2%',
                    '5. 提现申请将在1-3个工作日内处理完成',
                    '6. 严禁刷单、虚假邀请等违规行为，一经发现将冻结账户'
                ]
            ];
            
            return [RESULT_SUCCESS, '获取成功', $rules];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    /**
     * 获取最近邀请佣金用户（广告）
     */
    public function getRecentCommissionUsers($data = [])
    {
        $limit = isset($data['limit']) ? intval($data['limit']) : DB_LIST_ROWS;

        // 使用佣金来源表作为广告数据源
        $this->modelCommissionRecord->alias('cr');
        $this->modelCommissionRecord->join = [
            [SYS_DB_PREFIX . 'user u', 'u.id = cr.user_id', 'LEFT'],
            [SYS_DB_PREFIX . 'picture pic', 'pic.id = u.avatar_id', 'LEFT'],
            [SYS_DB_PREFIX . 'vip_order vo', 'vo.id = cr.order_id', 'LEFT'],
        ];

        $where = ['cr.status' => 1];
        $field = 'cr.amount, cr.create_time, u.nickname, IFNULL(pic.path, u.avatar_url) AS avatar, vo.package_type';
        $order = 'cr.create_time desc';

        $list = $this->modelCommissionRecord->getList($where, $field, $order, $limit);

        $planMap = [
            'month' => '月度会员',
            'year' => '年度会员',
            'three_year' => '三年会员'
        ];

        foreach ($list as $k => $row) {
            $nickname = $row['nickname'] ?? '';
            $masked = $this->maskName($nickname);
            $plan = $planMap[$row['package_type'] ?? ''] ?? '会员';
            $list[$k] = [
                'avatar' => $row['avatar'] ?? '',
                'nickname' => '恭喜会员 ' . $masked,
                'description' => '成功获得返利 ' . $plan,
                'amount' => sprintf('%.2f', floatval($row['amount'] ?? 0)),
                'time' => date('Y-m-d H:i', is_numeric($row['create_time']) ? $row['create_time'] : strtotime($row['create_time']))
            ];
        }

        return [RESULT_SUCCESS, '获取成功', ['list' => $list, 'has_more' => false]];
    }

    

    private function maskName($name)
    {
        $str = (string)$name;
        if ($str === '') return '';
        if (strpos($str, '*') !== false) return $str;
        $len = mb_strlen($str);
        if ($len <= 1) return $str;
        $first = mb_substr($str, 0, 1);
        $last = mb_substr($str, -1);
        return $first . '*' . $last;
    }

    /**
     * 用户余额流水列表
     */
    public function getUserBalanceList($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) { return []; }
        $where = ['user_id' => $userId];
        !empty($data['type']) && $where['type'] = $data['type'];
        $field = 'id,user_id,type,amount,balance_before,balance_after,description,related_id,status,create_time';
        $order = 'id desc';
        $paginate = $data['paginate'] ?? DB_LIST_ROWS;
        return $this->modelBalanceRecord->getList($where, $field, $order, $paginate);
    }

    /**
     * 用户佣金来源列表
     */
    public function getUserCommissionSourceList($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) { return []; }
        $this->modelCommissionRecord->alias('cr');
        $this->modelCommissionRecord->join = [
            [SYS_DB_PREFIX . 'user u', 'u.id = cr.user_id', 'LEFT'],
            [SYS_DB_PREFIX . 'user fu', 'fu.id = cr.from_user_id', 'LEFT'],
        ];
        $where = ['cr.user_id' => $userId];
        $field = 'cr.id,cr.user_id,cr.from_user_id,cr.order_id,cr.amount,cr.type,cr.description,cr.status,cr.create_time,u.nickname inviter_nickname,fu.nickname invitee_nickname';
        $order = 'cr.id desc';
        $paginate = $data['paginate'] ?? DB_LIST_ROWS;
        return $this->modelCommissionRecord->getList($where, $field, $order, $paginate);
    }

    /**
     * 订单佣金来源列表
     */
    public function getOrderCommissionList($data = [])
    {
        $orderId = $data['order_id'] ?? 0;
        if (!$orderId) { return []; }
        $this->modelCommissionRecord->alias('cr');
        $this->modelCommissionRecord->join = [
            [SYS_DB_PREFIX . 'user u', 'u.id = cr.user_id', 'LEFT'],
            [SYS_DB_PREFIX . 'user fu', 'fu.id = cr.from_user_id', 'LEFT'],
        ];
        $where = ['cr.order_id' => $orderId];
        $field = 'cr.id,cr.user_id,cr.from_user_id,cr.order_id,cr.amount,cr.type,cr.description,cr.status,cr.create_time,u.nickname inviter_nickname,fu.nickname invitee_nickname';
        $order = 'cr.id asc';
        $paginate = $data['paginate'] ?? DB_LIST_ROWS;
        return $this->modelCommissionRecord->getList($where, $field, $order, $paginate);
    }
}
